package com.gulangyu.trade.mvc;

import com.mycompany.yourtrade.enums.UserGrowth;
import com.mycompany.yourtrade.model.UserBean;
import com.mycompany.yourtrade.service.user.UserService;
import com.qunshang.common.SessionUtils;
import com.qunshang.common.UserBeanSession;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author xiaoguang
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public ModelAndView userRegister(ModelMap model) {
        ModelAndView mv = new ModelAndView("register");
        return mv;
    }

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public @ResponseBody
    String addUser(HttpServletRequest request,
            @RequestParam("mobile") String mobile,
            @RequestParam("password") String password,
            @RequestParam("mobileCaptcha") String mobileCaptcha) {

        String id = UUID.randomUUID().toString();
        if (StringUtils.isEmpty(mobile)) {
            return "手机号码不可为空";
        }
        UserBean userBean = new UserBean();
        userBean.setEnable(1);
        userBean.setId(id);
        userBean.setMobile(mobile);
        userBean.setPassword(password);
        try {
            Integer result = userService.addUserBean(id, mobile, BCrypt.hashpw(password, BCrypt.gensalt(10)), String.valueOf(UserGrowth.REGISTER), 0, 1);
            if (result > 0) {
                // 创建用户Session
                UserBeanSession session = new UserBeanSession(userBean);
                SessionUtils.setSession(request, session);
                logger.info("user created. [mobile={}]", userBean.getMobile());
                return "success";
            } else {
                logger.error("user create failed. [mobile={}]", userBean.getMobile());
                return "faile";
            }
        } catch (Exception e) {
            logger.error("user create failed. [mobile={},reason ={}]", userBean.getMobile(), e.getMessage());
            return "faile";
        }

    }
}
